import { selectOrder } from '@/services/orders';
import { selectByGoodsid } from '@/services/stock';
import { addStockOut } from '@/services/stockout';
import { Button, Form, Input, message, Modal, Select } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import styles from '../index.less';

type Props = {
  visible: boolean;
  handleCancel: () => void;
  handleNew: () => void;
  orderId: string;
  getList: () => void;
};

const CreateNew: React.FC<Props> = ({ visible, handleCancel, orderId, getList }) => {
  const [form] = Form.useForm();
  const { Option } = Select;
  const colorThem = localStorage.getItem('color') || '#1a7721';
  const [list, setList] = useState<any[]>([]);
  // const [goodsId, setGoodsId] = useState<string>('');
  // const [qtyValue, setQtyValue] = useState<number>(0);

  const getFlotList = useCallback(async () => {
    try {
      await selectByGoodsid({ goodsid: form.getFieldValue('goodsid') }).then((res) => {
        setList(res);
      });
    } catch (error) {
      console.log(error);
    }
  }, [form]);
  // form初始值
  const getInitValues = () => {
    return {
      orderid: orderId,
      logisticsCompany: '中国邮政',
    };
  };

  const selectById = useCallback(async () => {
    try {
      await selectOrder({ id: orderId }).then((res) => {
        form.setFieldsValue({ goodsid: res.goodsid, qty: res.qty });
        getFlotList();
      });
    } catch (error) {
      console.log(error);
    }
  }, [form, getFlotList, orderId]);

  useEffect(() => {
    selectById();
  }, [selectById]);

  const confirmSubmit = async (values: any) => {
    try {
      await addStockOut(values).then(() => {
        message.success('发货成功！');
        getList();
      });
      handleCancel();
      form.setFieldsValue({
        date: [],
        goodsid: '',
        flot: '',
        logisticsCompany: '中国邮政',
        logisticsCode: '',
      });
    } catch (error) {
      console.log(error);
    }
  };

  const onFinish = async () => {
    let values = await form.validateFields();

    Modal.confirm({
      title: '新建',
      centered: true,
      content: '请确认要提交的数据',
      okText: '确认',
      cancelText: '取消',
      onOk: () => confirmSubmit(values),
    });
  };

  return (
    <Modal
      visible={visible}
      onCancel={() => {
        handleCancel();
        form.setFieldsValue({
          orderid: '',
          goodsid: '',
          flot: '',
          logisticsCompany: '中国邮政',
          logisticsCode: '',
        });
      }}
      footer={[
        <>
          <Button
            onClick={() => {
              handleCancel();
              form.setFieldsValue({
                orderid: '',
                goodsid: '',
                flot: '',
                logisticsCompany: '中国邮政',
                logisticsCode: '',
              });
            }}
            className={styles.btnCancel}
          >
            取消
          </Button>
          <Button
            className={styles.btnSeal}
            style={{ background: `${colorThem}`, width: 120, color: '#fff' }}
            htmlType="submit"
            type="primary"
            onClick={onFinish}
          >
            新建
          </Button>
        </>,
      ]}
      closable={false}
      className={styles.modalsStyle}
      width={540}
      title={'新建出库单'}
      centered={true}
    >
      <div className={styles.modalContent}>
        <Form
          onFinish={onFinish}
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 40 }}
          initialValues={getInitValues()}
        >
          <Form.Item
            label="订单编号"
            name="orderid"
            validateTrigger="onBlur"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入订单编号
                  </div>
                ),
              },
              {
                pattern: new RegExp(
                  /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{36}/,
                ),
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    正确的订单编号
                  </div>
                ),
              },
            ]}
          >
            <Input placeholder="请输入订单编号" autoComplete="off" disabled />
          </Form.Item>
          <Form.Item
            label="商品编号"
            name="goodsid"
            validateTrigger="onBlur"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入商品编号
                  </div>
                ),
              },
              {
                pattern: new RegExp(
                  /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{36}/,
                ),
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    正确的订单编号
                  </div>
                ),
              },
            ]}
          >
            <Input placeholder="请输入商品编号" autoComplete="off" disabled />
          </Form.Item>
          <Form.Item
            label="入库批次"
            name="flot"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请选择入库批次
                  </div>
                ),
              },
            ]}
          >
            <Select placeholder="请选择入库批次">
              {list.map((item: any) => {
                return (
                  item.expireState !== '2' && (
                    <Option key={item.id} value={item.flot}>
                      {item.flot}
                      {item.expireState === '1' ? ' （临期）' : ''}
                    </Option>
                  )
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item
            label="出库数量"
            name="qty"
            validateTrigger="onBlur"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入出库数量
                  </div>
                ),
              },
            ]}
          >
            <Input placeholder="请输入出库数量" autoComplete="off" disabled />
          </Form.Item>
          <Form.Item
            label="物流公司"
            name="logisticsCompany"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请选择物流公司
                  </div>
                ),
              },
            ]}
          >
            <Select
              placeholder="请选择物流公司名称"
              // disabled={logisticsValues?.logisticsCompany}
            >
              <Option key={'1'} value="中国邮政">
                中国邮政
              </Option>
              <Option key={'2'} value="顺丰快递">
                顺丰快递
              </Option>
              <Option key={'3'} value="圆通速递">
                圆通速递
              </Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="物流单号"
            name="logisticsCode"
            validateTrigger="onBlur"
            rules={[
              {
                required: true,
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入物流单号
                  </div>
                ),
              },
              {
                pattern: new RegExp(/^[0-9A-Za-z]{10,20}$/),
                message: (
                  <div>
                    <img src={require('@/assets/images/error.png')} width={14} alt="错误" />
                    请输入10-20个数字或英文
                  </div>
                ),
              },
            ]}
          >
            <Input
              placeholder="请输入物流单号"
              autoComplete="off"
              // disabled={logisticsValues?.logisticsCode}
            />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
};

export default CreateNew;
